package com.object.module.lq.sys.service.impl;

import com.object.dao.sys.TTableDao;
import com.object.module.lq.sys.entity.TTableEntity;
import com.object.module.lq.sys.service.TTableService;
import com.object.utils.Q;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Service
public class TTableServiceImpl implements TTableService
{
    @Resource
    private TTableDao tTableDao;


    @Override
    public Q list(Map<String, Object> map)
    {
        String tableName = (String) map.get("tableName");
        List<TTableEntity> list = tTableDao.list(tableName);
        return Q.ok().q("data", list);
    }

    @Override
    public Q byTableNameSelect(String tableName)
    {
        List<Map<String, Object>> dataList = tTableDao.byTableNameSelect(tableName);
        return Q.ok().q("data", dataList);
    }

    @Resource
    private DataSource dataSource;

    @SneakyThrows
    @Override
    public Q saveSql(String tableName, String sql)
    {
        Connection connection = dataSource.getConnection();
        String dropSql = "drop table " + tableName;
        try {
            connection.prepareStatement(dropSql).executeUpdate();
        } catch (SQLException e) {
            System.out.println(e);
        }
        connection.prepareStatement(sql).executeUpdate();
        connection.close();
        return Q.ok();
    }
}
